import $store from '@/store/index.js'
export default {
	// 全局配置
	common:{
		baseUrl:"http://localhost:3000",
		header:{
			'Content-Type':'application/json;charset=UTF-8',
			'Content-Type':'application/x-www-form-urlencoded'
		},
		data:{},
		method:'GET',
		dataType:'json'
	},
	// 请求 返回promise
	request(options = {}){
		// 组织参数
		options.url = this.common.baseUrl + options.url
		options.header = options.header || this.common.header
		options.data = options.data || this.common.data
		options.method = options.method || this.common.method
		options.dataType = options.dataType || this.common.dataType
		
		if(options.token){
			options.header = { authorization : $store.state.login.tokenx }
			if (!options.header.authorization) {
				uni.showToast({
					title: '您还没有登录，请立刻登录',
					icon: 'none',
					duration: 2000,
					success() {
						return uni.switchTab({
						    url: '/pages/my/my'
						});
					}
				});
			}
		}
		
		// 请求
		return new Promise((res,rej)=>{
			// 请求之前... todo
			// 请求中...
			uni.request({
				...options,
				success: (result) => {
					if(result.data.code === 4402 || result.data.code === 4403){
						console.log(result.data.code)
						$store.state.login.tokenx="";
						$store.state.login.userinfox={};
						uni.clearStorage();
						uni.showToast({
							title: result.data.msg,
							icon: 'none'
						});
						setTimeout(()=>{
							return uni.switchTab({
							    url: '/pages/my/my'
							});
						},2000)
					}else{
						// 服务端失败
						if(result.statusCode !== 200){
							if (options.toast !== false) {
								uni.showToast({
									title: result.data.msg || '服务端失败',
									icon: 'none'
								});
							}
							return rej(result.data) 
						}
						let data = result.data
						res(data)
					}
				},
				fail: (error) => {
					uni.showToast({
						title: error.errMsg || '请求失败',
						icon: 'none'
					});
					return rej()
				}
			});
		})
	},
	// get请求
	get(url,data = {},options = {}){
		options.url = url
		options.data = data
		options.method = 'GET'
		return this.request(options)
	},
	// post请求
	post(url,data = {},options = {}){
		options.url = url
		options.data = data
		options.method = 'POST'
		return this.request(options)
	},
	// delete请求
	del(url,data = {},options = {}){
		options.url = url
		options.data = data
		options.method = 'DELETE'
		return this.request(options)
	}
}